<template>
  <div class="category">
      <!-- 搜索框 -->
    <van-search v-model="searchData" input-align="center" placeholder="商品搜索 共239亿款好物" />
    <van-tree-select
      :items="catalogList"
      :main-active-index.sync="activeIndex"
      height="calc(100vh - 104px)"
      @click-nav="changeRight">
          <template #content>
            <van-image width="100%" height="80" :src="bannerImg"/>
            <van-grid :column-num="3">
              <van-grid-item v-for="(item, index) in subCategoryList" :key="index" :icon="item.wap_banner_url" :text="item.name" :to="'/categoryList/'+item.id" />
            </van-grid>
          </template>
      </van-tree-select>
    <Navigation></Navigation>
  </div>
</template>

<script>
import Navigation from './Navigation.vue'
import Vue from 'vue'
import { TreeSelect } from 'vant'

Vue.use(TreeSelect)
export default {
  data () {
    return {
      searchData: '',
      catalogList: [],
      activeIndex: 0,
      subCategoryList: [],
      bannerImg: ''
    }
  },
  async created () {
    const { data: res } = await this.$http.get('catalog/index')
    const arr = []
    res.data.categoryList.forEach(item => {
      item.text = item.name
      arr.push(item)
    })
    this.catalogList = arr
    this.bannerImg = res.data.currentCategory.banner_url
  },
  components: {
    Navigation
  },
  methods: {
    changeRight (index) {
      this.activeIndex = index
    }
  },
  watch: {
    activeIndex: async function () {
      if (this.catalogList.length !== 0) {
        const id = this.catalogList[this.activeIndex].id
        const { data: res } = await this.$http.get('catalog/current', { params: { id } })
        this.subCategoryList = res.data.currentCategory.subCategoryList
        this.bannerImg = this.catalogList[this.activeIndex].img_url
      } else {
        this.subCategoryList = []
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
